package com.xsq.wifi.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.orhanobut.hawk.Hawk;
import com.xsq.wifi.activity.DeviceVideoListActivity;
import com.xsq.wifi.activity.WifiListActivity;
import com.xsq.wifi.adapter.DeviceAdapter;
import com.xsq.wifi.callback.Callbacks;
import com.xsq.wifi.databinding.FragmentDeviceBinding;
import com.xsq.wifi.model.DeviceModel;
import com.xsq.wifi.model.WifiListModel;
import com.xsq.wifi.utils.ProgressDialogUtil;
import com.xsq.wifi.utils.ProtocolConstants;
import com.xsq.wifi.utils.SSDPScanner;
import com.xsq.wifi.utils.ToastUtil;
import com.xsq.wifi.utils.WifiListFetcher;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 编写人：李振德
 * 创建时间：2025/5/7
 */
public class DeviceFragment extends Fragment {

    private FragmentDeviceBinding binding;
    private DeviceAdapter deviceAdapter;
    private List<DeviceModel> deviceModels = new ArrayList<>();
    private String device_ip;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentDeviceBinding.inflate(inflater, container, false);
        View view = binding.getRoot();
        binding.addImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(TextUtils.isEmpty(device_ip)){
                    ToastUtil.show(getActivity(),"暂无在线设备");
                }else{
                    ProgressDialogUtil.showProgressDialog(getActivity());
                    //获取wifi列表
                    WifiListFetcher.fetchWifiList(device_ip, ProtocolConstants.CMD_WIFISCAN_GET,new  Callbacks.WifiListCallback() {
                        @Override
                        public void onSuccess(List<WifiListModel> wifiList) {
                            // 更新UI显示WiFi列表
                            getActivity().runOnUiThread(() -> {
                                Intent intent = new Intent(getActivity(), WifiListActivity.class);
                                intent.putExtra("wifi_list", (Serializable) wifiList);
                                intent.putExtra("device_ip", device_ip);
                                startActivity(intent);
                            });
                            ProgressDialogUtil.dismiss();
                        }

                        @Override
                        public void onFailure(String error) {
                            getActivity().runOnUiThread(() -> Toast.makeText(getActivity(), "获取失败: " + error, Toast.LENGTH_SHORT).show());
                            ProgressDialogUtil.dismiss();
                        }
                    });
                }
            }
        });
        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(),2);
        binding.recyclerDevice.setLayoutManager(layoutManager);
        deviceAdapter = new DeviceAdapter(deviceModels,getActivity());
        //详情
        deviceAdapter.setOnItemClickListener(new DeviceAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(String ip,String uuid) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), DeviceVideoListActivity.class);
                intent.putExtra("device_ip", ip);
                intent.putExtra("device_uuid", uuid);
                startActivity(intent);
            }
        });
        binding.recyclerDevice.setAdapter(deviceAdapter);
        // 设置下拉刷新监听
        binding.swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // 触发刷新逻辑
                initdata();
            }
        });

        Set<String> savedUuids = Hawk.get("uuid_set", Collections.emptySet());
        for (String uuid : savedUuids) {
            Log.d("UUID", "遍历UUID: " + uuid);
            int lastDashIndex = uuid.lastIndexOf("-");
            String macAddress = uuid.substring(lastDashIndex + 1);
            DeviceModel deviceModel = new DeviceModel("1",macAddress,uuid,"BEVERG_"+macAddress.toUpperCase(),"",false);
            deviceModels.add(deviceModel);
        }
        deviceAdapter.notifyDataSetChanged();
        // 设置下拉刷新监听
        binding.swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // 触发刷新逻辑
                initdata();
            }
        });
        initdata();
        return view;
    }

    public void initdata(){
        SSDPScanner scanner = new SSDPScanner(getActivity());
        scanner.startDiscovery(new SSDPScanner.OnDeviceFoundListener() {
            @Override
            public void onDeviceFound(String deviceIp, String deviceUrl, String rawResponse) {
                getActivity().runOnUiThread(() -> {
                    Log.d("SSDP", "设备IP: " + deviceIp);
                    Log.d("SSDP", "设备URL: " + deviceUrl);
                    Log.d("SSDP", "完整响应:\n" + rawResponse);
                    if(rawResponse.contains("ESP32")){
                        device_ip = deviceIp;
                        // 找到USN行
                        int usnIndex = rawResponse.indexOf("USN:");
                        if (usnIndex != -1) {
                            int uuidStart = rawResponse.indexOf("uuid:", usnIndex) + 5; // 5是"uuid:"的长度
                            int uuidEnd = rawResponse.indexOf("::", uuidStart);
                            String uuid = rawResponse.substring(uuidStart, uuidEnd);
                            Set<String> uuidSet = Hawk.get("uuid_set", new HashSet<>());
                            //自动去重添加
                            if (!uuidSet.contains(uuid)) {
                                uuidSet.add(uuid);
                                Hawk.put("uuid_set", uuidSet); // 保存更新后的Set
                                Log.d("UUID", "新增UUID: " + uuid);
                            } else {
                                Log.d("UUID", "UUID已存在: " + uuid);
                            }
                            System.out.println("提取的UUID: " + uuid); // 输出: 38323636-4558-4dda-9188-cda0e697bacc
                            int lastDashIndex = uuid.lastIndexOf("-");
                            String macAddress = uuid.substring(lastDashIndex + 1);
                            deviceAdapter.addOrUpdateDevice(new DeviceModel(deviceIp,macAddress,uuid,"BEVERG_"+macAddress.toUpperCase(),"",true));
                        }
                    }else{
                        Log.d("SSDP", "非我们的设备");
                    }
                    binding.swipeRefresh.setRefreshing(false);
                });
            }

            @Override
            public void onDiscoveryFinished(boolean hasDevices) {
                binding.swipeRefresh.setRefreshing(false);
            }

            @Override
            public void onError(Exception e) {
                binding.swipeRefresh.setRefreshing(false);
            }
        });
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
